package com.lxh.mp.handler;

import com.lxh.mp.builder.ImgBuilder;
import com.lxh.mp.builder.TextBuilder;
import com.lxh.mp.builder.VideoBuilder;
import com.lxh.mp.utils.JsonUtils;
import me.chanjar.weixin.common.api.WxConsts;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.common.session.WxSessionManager;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage;
import me.chanjar.weixin.mp.builder.outxml.ImageBuilder;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * created by lanxinghua@2dfire.com on 2020/2/21
 */
@Component
public class MsgHandler extends AbstractHandler {
    @Override
    public WxMpXmlOutMessage handle(WxMpXmlMessage wxMessage, Map<String, Object> context, WxMpService wxMpService, WxSessionManager sessionManager) throws WxErrorException {
        logger.info("accessToken："+wxMpService.getAccessToken(false));
        if (!wxMessage.getMsgType().equals(WxConsts.XmlMsgType.EVENT)) {
            //TODO 可以选择将消息保存到本地
        }

        // 在线客服：当用户输入关键词如“你好”，“客服”等，并且有客服在线时，把消息转发给在线客服
        try {
            if (StringUtils.startsWithAny(wxMessage.getContent(), "你好", "客服")
                    && wxMpService.getKefuService().kfOnlineList().getKfOnlineList().size() > 0) {
                return WxMpXmlOutMessage.TRANSFER_CUSTOMER_SERVICE()
                        .fromUser(wxMessage.getToUser())
                        .toUser(wxMessage.getFromUser()).build();
            }
        } catch (WxErrorException e) {
            e.printStackTrace();
        }

        // 图片发送
        if (StringUtils.startsWith(wxMessage.getContent(), "图片")){
            String mediaId = "yuuZqn-4X8dfvA9hN3uR2B74elgihVB4y3ZyuD2-DCLxiY3s6JkgT5TAnwXMJzwL";
            return new ImgBuilder().build(mediaId, wxMessage, wxMpService);
        }

        // 视频发送
        if (StringUtils.startsWith(wxMessage.getContent(), "视频")){
            String mediaId = "QJaotmwEvopEiz19NNSOFMip97knJVBvztL6T7QAJjUBezfq02Q_r4At92SycTHI";
            return new VideoBuilder().build(mediaId, wxMessage, wxMpService);
        }

        // 组装回复消息
        String content = "收到信息内容：" + JsonUtils.toJson(wxMessage);
        return new TextBuilder().build(content, wxMessage, wxMpService);
    }
}
